﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Reflection;
using TiaoTiaoCode.Common.Attributes;

namespace TiaoTiaoCode.Common.Extensions
{
    /// <summary>
    /// DataTable扩展
    /// </summary>
    public static class DataTableEx
    {
        /// <summary>
        /// DataTable转List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T>? TiaoTiaoToModelByFieldMapping<T>(this DataTable dt)
        {
            var type = typeof(T);

            if (dt == null || dt.Rows.Count <= 0) return null;

            var result = new List<T>();

            foreach (DataRow dr in dt.Rows)
            {
                // 第一单元格为空，跳过，视为空行                
                if (dr == null || string.IsNullOrWhiteSpace(dr[0].ToString())) continue;

                T obj = Activator.CreateInstance<T>();

                foreach (DataColumn dc in dr.Table.Columns)
                {
                    foreach (PropertyInfo pi in type.GetProperties())
                    {
                        var attr = (FieldMappingAttribute)pi.GetCustomAttribute(typeof(FieldMappingAttribute));
                        if (attr == null) continue;

                        if (!attr.Fields.Contains(dc.ColumnName)) continue;

                        switch (pi.PropertyType.Name.ToUpper())
                        {
                            case "INT32":
                                if (dr[dc.ColumnName] == DBNull.Value)
                                    pi.SetValue(obj, null, null);
                                else
                                    pi.SetValue(obj, int.Parse(dr[dc.ColumnName].ToString()), null);
                                break;
                            case "DECIMAL":
                                if (dr[dc.ColumnName] == DBNull.Value)
                                    pi.SetValue(obj, null, null);
                                else
                                    pi.SetValue(obj, decimal.Parse(dr[dc.ColumnName].ToString()), null);
                                break;
                            default:
                                if (pi.PropertyType.FullName.ToUpper().Contains("NULLABLE") && dr[dc.ColumnName] == null)
                                    pi.SetValue(obj, null, null);
                                else if (pi.PropertyType.FullName.ToUpper().Contains("NULLABLE") && pi.PropertyType.FullName.ToUpper().Contains("DECIMAL"))
                                    pi.SetValue(obj, (decimal?)decimal.Parse(dr[dc.ColumnName].ToString()), null);
                                else
                                    pi.SetValue(obj, dr[dc.ColumnName], null);
                                break;
                        }
                        break;
                    }
                }

                result.Add(obj);
            }

            return result;
        }

        /// <summary>
        /// DataTable转List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T>? TiaoTiaoToModel<T>(this DataTable dt)
        {
            var type = typeof(T);

            if (dt == null || dt.Rows.Count <= 0) return null;

            var result = new List<T>();

            foreach (DataRow dr in dt.Rows)
            {
                // 第一单元格为空，跳过，视为空行                
                if (dr == null || string.IsNullOrWhiteSpace(dr[0].ToString())) continue;

                T obj = Activator.CreateInstance<T>();

                foreach (DataColumn dc in dr.Table.Columns)
                {
                    foreach (PropertyInfo pi in type.GetProperties())
                    {
                        switch (pi.PropertyType.Name.ToUpper())
                        {
                            case "INT32":
                                if (dr[dc.ColumnName] == DBNull.Value)
                                    pi.SetValue(obj, null, null);
                                else
                                    pi.SetValue(obj, int.Parse(dr[dc.ColumnName].ToString()), null);
                                break;
                            case "DECIMAL":
                                if (dr[dc.ColumnName] == DBNull.Value)
                                    pi.SetValue(obj, null, null);
                                else
                                    pi.SetValue(obj, decimal.Parse(dr[dc.ColumnName].ToString()), null);
                                break;
                            default:
                                if (pi.PropertyType.FullName.ToUpper().Contains("NULLABLE") && dr[dc.ColumnName] == null)
                                    pi.SetValue(obj, null, null);
                                else if (pi.PropertyType.FullName.ToUpper().Contains("NULLABLE") && pi.PropertyType.FullName.ToUpper().Contains("DECIMAL"))
                                    pi.SetValue(obj, (decimal?)decimal.Parse(dr[dc.ColumnName].ToString()), null);
                                else
                                    pi.SetValue(obj, dr[dc.ColumnName], null);
                                break;
                        }
                        break;
                    }
                }

                result.Add(obj);
            }

            return result;
        }

        /// <summary>
        /// List转DataTable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static DataTable TiaoTiaoToDataTable<T>(this List<T> list)
        {
            if (list == null || list.Count <= 0) return new DataTable();

            var dt = new DataTable();
            var type = typeof(T);
            var piList = new Dictionary<int, string>();

            var i = 0;
            foreach (var pi in type.GetProperties())
            {
                piList.Add(i++, pi.Name);
            }

            piList.OrderBy(t => t.Key).ToList().ForEach(kv => dt.Columns.Add(kv.Value));

            foreach (var item in list)
            {
                var row = dt.NewRow();
                foreach (var pi in type.GetProperties())
                {
                    var fieldName = pi.Name;
                    row[fieldName] = pi.GetValue(item, null);
                }
                dt.Rows.Add(row);
            }

            return dt;
        }

        /// <summary>
        /// List转DataTable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static DataTable TiaoTiaoToDataTable2<T>(this List<T> list)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
            DataTable dt = new DataTable();
            for (int i = 0; i < properties.Count; i++)
            {
                PropertyDescriptor property = properties[i];
                dt.Columns.Add(property.Name, property.PropertyType);
            }
            object[] values = new object[properties.Count];
            foreach (T item in list)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = properties[i].GetValue(item);
                }
                dt.Rows.Add(values);
            }
            return dt;
        }
    }
}
